package com.sqm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.sqm.entity.User;
import com.sqm.entity.dto.UserDTO;
import com.sqm.entity.vo.UserVO;
import com.sqm.mapper.UserMapper;
import com.sqm.service.UserService;
import com.sqm.utils.TokenUtils;
import jakarta.annotation.Resource;

import org.springframework.stereotype.Service;

/**
 * 功能:
 * 作者: 沙琪马
 * 日期: 2024/5/21 17:03
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 登录
     * @param userDTO
     * @return
     */
    @Override
    public UserVO login(UserDTO userDTO) {
        // 1. 根据用户名查询用户
        User user = userMapper.selectByName(userDTO.getUsername());
        if(user == null){
            throw new RuntimeException("用户名或密码错误");
        }
        // 2.生成token
        String token = TokenUtils.createToken(user.getId().toString(), user.getPassword());

        // 3.封装数据
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        userVO.setToken(token);

        return userVO;
    }
}
